const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    songId: null,
    songInfo: {},
    lyric: "",
    lyricList: [],
    currentLyricIndex: 0,
    playProgress: 0,
    currentTime: "00:00",
    totalTime: "00:00",
    isPlaying: false,
    isFavorite: false,
    sliderValue: 0,
    sliderChanging: false,
    showLyric: true, // 是否显示歌词
    playMode: "list", // 播放模式: list(列表循环), single(单曲循环), random(随机播放)
    playModeIcon: "🔁", // 播放模式图标
    playModeImage: "/assets/play-in-order.png", // 新增：播放模式图片路径
    isHeartbeatMode: false, // 心动模式状态
    heartbeatSongs: [], // 心动模式歌曲列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取歌曲ID
    const songId = options.id;
    if (!songId) {
      wx.showToast({
        title: "歌曲ID不存在",
        icon: "none",
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    this.setData({ songId });

    // 获取歌曲详情
    this.getSongDetail(songId);

    // 获取歌词
    this.getLyric(songId);

    // 初始化音频管理器
    this.setupAudioManager();

    // 检查是否收藏
    this.checkIsFavorite(songId);

    // 获取保存的播放模式
    const savedPlayMode = wx.getStorageSync("playMode") || "list";
    this.setPlayModeIcon(savedPlayMode);

    // 恢复心动模式状态
    const heartbeatMode = wx.getStorageSync("heartbeatMode") || false;
    if (heartbeatMode) {
      this.setData({ isHeartbeatMode: heartbeatMode });
      // 如果开启了心动模式，加载相似歌曲
      if (heartbeatMode) {
        this.loadSimilarSongs(songId);
      }
    }

    // 注册歌曲变化的回调函数
    app.songChangeCallback = this.handleSongChange.bind(this);
  },

  // 处理歌曲变化的回调函数
  handleSongChange: function (song) {
    if (!song || !song.id) return;

    // 更新当前的songId
    const newSongId = song.id.toString();

    // 如果歌曲ID已经变化，更新页面数据
    if (newSongId !== this.data.songId) {
      this.setData({ songId: newSongId });

      // 获取新歌曲的详细信息
      this.getSongDetail(newSongId);

      // 获取新歌曲的歌词
      this.getLyric(newSongId);

      // 检查新歌曲是否已收藏
      this.checkIsFavorite(newSongId);

      // 如果开启了心动模式，加载相似歌曲
      if (this.data.isHeartbeatMode) {
        this.loadSimilarSongs(newSongId);
      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 更新播放状态
    this.updatePlayingStatus();

    // 定时更新进度
    this.startProgressTimer();

    // 重新注册歌曲变化的回调函数（防止被其他页面覆盖）
    app.songChangeCallback = this.handleSongChange.bind(this);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 清除定时器
    this.clearProgressTimer();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 清除定时器
    this.clearProgressTimer();

    // 清除回调函数引用，避免内存泄漏
    if (app.songChangeCallback === this.handleSongChange.bind(this)) {
      app.songChangeCallback = null;
    }
  },

  /**
   * 初始化音频管理器
   */
  setupAudioManager: function () {
    this.audioManager = wx.getBackgroundAudioManager();

    // 监听播放事件
    this.audioManager.onPlay(() => {
      this.setData({ isPlaying: true });
      this.startProgressTimer();
    });

    // 监听暂停事件
    this.audioManager.onPause(() => {
      this.setData({ isPlaying: false });
      this.clearProgressTimer();
    });

    // 监听停止事件
    this.audioManager.onStop(() => {
      this.setData({ isPlaying: false });
      this.clearProgressTimer();
    });

    // 监听播放结束事件
    this.audioManager.onEnded(() => {
      this.setData({ isPlaying: false, playProgress: 0, currentTime: "00:00" });
      this.clearProgressTimer();

      // 根据播放模式决定下一步操作
      if (this.data.playMode === "single") {
        // 单曲循环，重新播放当前歌曲
        this.playSong(this.data.songInfo);
      } else {
        // 列表循环或随机播放，播放下一首
        this.playNextSong();
      }
    });

    // 监听播放进度更新事件
    this.audioManager.onTimeUpdate(() => {
      if (this.data.sliderChanging) return;

      const currentTime = this.audioManager.currentTime;
      const duration = this.audioManager.duration;

      if (duration > 0) {
        const progress = (currentTime / duration) * 100;
        const formatCurrentTime = this.formatTime(currentTime);

        this.setData({
          playProgress: progress,
          currentTime: formatCurrentTime,
          sliderValue: progress,
        });

        // 更新当前歌词
        this.updateCurrentLyric(currentTime);
      }
    });
  },

  /**
   * 获取歌曲详情
   */
  getSongDetail: function (songId) {
    const token = wx.getStorageSync("access_token");
    const that = this;

    wx.request({
      url: `${app.globalData.apiBaseUrl}/song/detail`,
      method: "GET",
      data: {
        ids: songId,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        if (res.data && res.data.songs && res.data.songs.length > 0) {
          const songInfo = res.data.songs[0];
          const totalTime = that.formatTime(songInfo.dt / 1000);

          that.setData({
            songInfo,
            totalTime,
          });

          // 如果当前歌曲正在播放，更新进度
          if (
            app.globalData.nowPlaying &&
            app.globalData.nowPlaying.id === parseInt(songId)
          ) {
            that.updatePlayingStatus();
          } else {
            // 否则播放这首歌
            that.playSong(songInfo);
          }
        } else {
          wx.showToast({
            title: "获取歌曲详情失败",
            icon: "none",
          });
        }
      },
      fail(err) {
        console.error("获取歌曲详情失败:", err);
        wx.showToast({
          title: "获取歌曲详情失败",
          icon: "none",
        });
      },
    });
  },

  /**
   * 获取歌词
   */
  getLyric: function (songId) {
    const token = wx.getStorageSync("access_token");
    const that = this;

    // 明确使用HTTP域名
    wx.request({
      url: "https://smartsound.top/lyric",
      method: "GET",
      data: {
        id: songId,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        if (res.data && res.data.lrc && res.data.lrc.lyric) {
          const lyric = res.data.lrc.lyric;
          // 解析歌词
          const lyricList = that.parseLyric(lyric);
          that.setData({
            lyric,
            lyricList,
          });
        } else {
          that.setData({
            lyric: "暂无歌词",
            lyricList: [{ time: 0, content: "暂无歌词" }],
          });
        }
      },
      fail(err) {
        console.error("获取歌词失败:", err);
        console.log("尝试使用备用方式获取歌词");

        // 备用方式，使用代理路径
        wx.request({
          url: `${app.globalData.deviceApiBaseUrl}/api/v1/proxy_lyric`,
          method: "GET",
          data: {
            id: songId,
          },
          header: {
            Authorization: token ? `Bearer ${token}` : "",
            "content-type": "application/json",
          },
          success(res) {
            if (res.data && res.data.lrc && res.data.lrc.lyric) {
              const lyric = res.data.lrc.lyric;
              // 解析歌词
              const lyricList = that.parseLyric(lyric);
              that.setData({
                lyric,
                lyricList,
              });
            } else {
              that.setData({
                lyric: "暂无歌词",
                lyricList: [{ time: 0, content: "暂无歌词" }],
              });
            }
          },
          fail(backupErr) {
            console.error("备用方式获取歌词也失败:", backupErr);
            that.setData({
              lyric: "获取歌词失败",
              lyricList: [{ time: 0, content: "获取歌词失败" }],
            });
          },
        });
      },
    });
  },

  /**
   * 解析歌词
   */
  parseLyric: function (lyric) {
    const lines = lyric.split("\n");
    const pattern = /\[\d{2}:\d{2}.\d{2,3}\]/g;
    const result = [];

    lines.forEach((line) => {
      if (line) {
        const timeStr = line.match(pattern);
        if (!timeStr) return;

        const content = line.replace(pattern, "").trim();
        if (content) {
          const time = timeStr[0];
          const min = parseInt(time.slice(1, 3));
          const sec = parseInt(time.slice(4, 6));
          const millisec = parseInt(time.slice(7, 9));

          result.push({
            time: min * 60 + sec + millisec / 100, // 转换为秒
            content,
          });
        }
      }
    });

    // 按时间排序
    result.sort((a, b) => a.time - b.time);
    return result;
  },

  /**
   * 更新当前歌词
   */
  updateCurrentLyric: function (currentTime) {
    const { lyricList } = this.data;
    if (lyricList.length === 0) return;

    let index = 0;
    for (let i = 0; i < lyricList.length; i++) {
      if (currentTime < lyricList[i].time) {
        index = i - 1;
        break;
      }
    }

    if (index < 0) index = 0;
    if (index >= lyricList.length) index = lyricList.length - 1;

    if (this.data.currentLyricIndex !== index) {
      this.setData({ currentLyricIndex: index });

      // 添加代码，在歌词滚动后保持居中
      // 使用nextTick确保DOM更新后再计算滚动位置
      wx.nextTick(() => {
        const query = wx.createSelectorQuery();
        query.select(".lyric-item.active").boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec((res) => {
          if (res && res[0] && res[1]) {
            // 当前元素不需要额外调整，scroll-into-view已经将它滚动到视野内
            // 居中显示已经通过CSS padding实现
          }
        });
      });
    }
  },

  /**
   * 播放歌曲
   */
  playSong: function (song) {
    // 调用app.js中的方法播放歌曲
    app.playSong({
      id: song.id,
      name: song.name,
      artist: song.ar[0].name,
      picUrl: song.al.picUrl,
      duration: song.dt / 1000,
      album: song.al.name,
      // 提供完整的歌手信息和歌曲时长，以便上传播放记录
      ar: song.ar,
      dt: song.dt,
    });

    this.setData({ isPlaying: true });
  },

  /**
   * 暂停/继续播放
   */
  togglePlay: function () {
    if (this.data.isPlaying) {
      this.audioManager.pause();
      this.setData({ isPlaying: false });
    } else {
      this.audioManager.play();
      this.setData({ isPlaying: true });
    }
  },

  /**
   * 播放上一首
   */
  playPrevSong: function () {
    app.playPrevSong();
  },

  /**
   * 播放下一首
   */
  playNextSong: function () {
    // 如果开启了心动模式且有可用的相似歌曲
    if (this.data.isHeartbeatMode && this.data.heartbeatSongs.length > 0) {
      // 从心动歌曲列表中随机选择一首
      const randomIndex = Math.floor(
        Math.random() * this.data.heartbeatSongs.length
      );
      const nextSong = this.data.heartbeatSongs[randomIndex];

      // 播放选中的歌曲
      if (nextSong && nextSong.id) {
        app.playSongById(nextSong.id);
      } else {
        // 如果没有可用的心动歌曲，则使用默认的下一首
        app.playNextSong();
      }
    } else {
      // 默认播放逻辑
      app.playNextSong();
    }
  },

  /**
   * 切换收藏状态
   */
  toggleFavorite: function () {
    const { songId, isFavorite } = this.data;
    const token = wx.getStorageSync("access_token");
    const that = this;

    if (!token) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      return;
    }

    // 先更新UI状态，提供即时反馈
    this.setData({
      isFavorite: !isFavorite,
    });

    // 调用喜欢音乐接口
    wx.request({
      url: `${app.globalData.apiBaseUrl}/like`,
      method: "GET",
      data: {
        id: songId,
        like: !isFavorite,
      },
      header: {
        Authorization: `Bearer ${token}`,
        "content-type": "application/json",
      },
      success(res) {
        if (res.data && res.data.code === 200) {
          wx.showToast({
            title: that.data.isFavorite ? "已添加到我喜欢的音乐" : "已取消喜欢",
            icon: "none",
          });
        } else {
          // 如果接口调用失败，恢复原来的状态
          that.setData({
            isFavorite: isFavorite,
          });
          wx.showToast({
            title: "操作失败，请重试",
            icon: "none",
          });
        }
      },
      fail(err) {
        console.error("喜欢音乐操作失败:", err);
        // 如果接口调用失败，恢复原来的状态
        that.setData({
          isFavorite: isFavorite,
        });
        wx.showToast({
          title: "操作失败，请重试",
          icon: "none",
        });
      },
    });
  },

  /**
   * 检查歌曲是否已收藏
   */
  checkIsFavorite: function (songId) {
    const token = wx.getStorageSync("access_token");
    const that = this;

    if (!token) return;

    // 调用获取喜欢音乐列表接口
    wx.request({
      url: `${app.globalData.apiBaseUrl}/song/like/check`,
      method: "GET",
      data: {
        ids: `[${songId}]`,
      },
      header: {
        Authorization: `Bearer ${token}`,
        "content-type": "application/json",
      },
      success(res) {
        if (res.data && res.data.ids && res.data.ids.includes(Number(songId))) {
          that.setData({
            isFavorite: true,
          });
        }
      },
      fail(err) {
        console.error("检查喜欢状态失败:", err);
      },
    });
  },

  /**
   * 滑块改变中
   */
  onSliderChanging: function (e) {
    this.setData({
      sliderChanging: true,
      sliderValue: e.detail.value,
      playProgress: e.detail.value,
    });
  },

  /**
   * 滑块改变后
   */
  onSliderChange: function (e) {
    const progress = e.detail.value;
    const duration = this.audioManager.duration;
    const currentTime = (duration * progress) / 100;

    this.audioManager.seek(currentTime);
    this.setData({
      sliderChanging: false,
      currentTime: this.formatTime(currentTime),
    });
  },

  /**
   * 更新播放状态
   */
  updatePlayingStatus: function () {
    if (
      app.globalData.nowPlaying &&
      app.globalData.nowPlaying.id === parseInt(this.data.songId)
    ) {
      this.setData({
        isPlaying: app.globalData.isPlaying,
      });

      if (this.audioManager) {
        const currentTime = this.audioManager.currentTime || 0;
        const duration = this.audioManager.duration || 0;

        if (duration > 0) {
          const progress = (currentTime / duration) * 100;
          this.setData({
            playProgress: progress,
            currentTime: this.formatTime(currentTime),
            totalTime: this.formatTime(duration),
            sliderValue: progress,
          });
        }
      }
    }
  },

  /**
   * 开始进度定时器
   */
  startProgressTimer: function () {
    this.clearProgressTimer();
    this.progressTimer = setInterval(() => {
      this.updatePlayingStatus();
    }, 1000);
  },

  /**
   * 清除进度定时器
   */
  clearProgressTimer: function () {
    if (this.progressTimer) {
      clearInterval(this.progressTimer);
      this.progressTimer = null;
    }
  },

  /**
   * 格式化时间
   */
  formatTime: function (time) {
    if (isNaN(time)) return "00:00";

    const min = Math.floor(time / 60);
    const sec = Math.floor(time % 60);

    return `${min < 10 ? "0" + min : min}:${sec < 10 ? "0" + sec : sec}`;
  },

  /**
   * 切换封面/歌词显示
   */
  toggleView: function () {
    this.setData({
      showLyric: !this.data.showLyric,
    });
  },

  /**
   * 设置播放模式图标
   */
  setPlayModeIcon: function (mode) {
    let icon = "🔁"; // 默认列表循环 - 保留以兼容原有代码
    let imagePath = "/assets/play-in-order.png"; // 默认列表循环图片

    if (mode === "single") {
      icon = "🔂"; // 单曲循环
      imagePath = "/assets/single-cycle.png"; // 单曲循环图片
    } else if (mode === "random") {
      icon = "🔀"; // 随机播放
      imagePath = "/assets/random-play.png"; // 随机播放图片
    }

    this.setData({
      playMode: mode,
      playModeIcon: icon, // 保留更新这个属性以兼容原有代码
      playModeImage: imagePath, // 更新图片路径
    });

    // 保存播放模式到本地
    wx.setStorageSync("playMode", mode);

    // 更新全局播放模式
    if (app.globalData) {
      app.globalData.playMode = mode;
    }
  },

  /**
   * 切换播放模式
   */
  changePlayMode: function () {
    const currentMode = this.data.playMode;
    let newMode = "list";

    // 循环切换：列表循环 -> 单曲循环 -> 随机播放 -> 列表循环
    if (currentMode === "list") {
      newMode = "single";
    } else if (currentMode === "single") {
      newMode = "random";
    }

    this.setPlayModeIcon(newMode);

    // 显示提示
    let modeText = "列表循环";
    if (newMode === "single") {
      modeText = "单曲循环";
    } else if (newMode === "random") {
      modeText = "随机播放";
    }

    wx.showToast({
      title: modeText,
      icon: "none",
      duration: 1500,
    });
  },

  /**
   * 显示播放列表
   */
  showPlaylist: function () {
    // 获取全局播放列表
    const currentSongList = app.globalData.currentSongList || [];

    // 如果没有播放记录
    if (!currentSongList || currentSongList.length === 0) {
      wx.showToast({
        title: "暂无播放记录",
        icon: "none",
      });
      return;
    }

    // 显示加载状态
    wx.showLoading({
      title: "获取播放列表...",
    });

    // 处理最近播放的10首歌曲
    const recentSongs = currentSongList.slice(0, 10).map((song) => {
      return {
        id: song.id,
        name: song.name || song.title,
        artist:
          song.artist ||
          (song.ar && song.ar[0] && song.ar[0].name) ||
          (song.artists && song.artists[0] && song.artists[0].name) ||
          "未知歌手",
        coverUrl:
          song.picUrl ||
          (song.al && song.al.picUrl) ||
          (song.album && song.album.picUrl) ||
          "/assets/music-icon.png",
      };
    });

    wx.hideLoading();

    // 显示播放列表弹窗
    this.showPlaylistModal(recentSongs);
  },

  /**
   * 显示播放列表弹窗
   */
  showPlaylistModal: function (songs) {
    // 如果没有歌曲，提示用户
    if (!songs || songs.length === 0) {
      wx.showToast({
        title: "暂无播放记录",
        icon: "none",
      });
      return;
    }

    // 构建歌曲列表内容
    let content = "";
    songs.forEach((song, index) => {
      content += `${index + 1}. ${song.name} - ${song.artist}\n`;
    });

    // 使用微信小程序的模态弹窗显示播放列表
    wx.showModal({
      title: "最近播放",
      content: content,
      showCancel: true,
      cancelText: "关闭",
      confirmText: "查看更多",
      success: (res) => {
        if (res.confirm) {
          // 用户点击"查看更多"，可以跳转到完整播放列表页面
          wx.showToast({
            title: "完整播放列表功能开发中",
            icon: "none",
          });
        }
      },
    });
  },

  /**
   * 分享歌曲
   */
  onShareAppMessage: function () {
    const { songInfo } = this.data;
    return {
      title: `${songInfo.name} - ${songInfo.ar[0].name}`,
      path: `/pages/song/song?id=${this.data.songId}`,
      imageUrl: songInfo.al.picUrl,
    };
  },

  /**
   * 切换心动模式
   */
  toggleHeartbeatMode: function () {
    const newState = !this.data.isHeartbeatMode;

    this.setData({ isHeartbeatMode: newState });

    // 保存心动模式状态
    wx.setStorageSync("heartbeatMode", newState);

    if (newState) {
      // 打开心动模式
      wx.showToast({
        title: "心动模式已开启",
        icon: "none",
        duration: 1500,
      });

      // 加载相似歌曲
      this.loadSimilarSongs(this.data.songId);
    } else {
      // 关闭心动模式
      wx.showToast({
        title: "心动模式已关闭",
        icon: "none",
        duration: 1500,
      });

      // 清空心动歌曲列表
      this.setData({ heartbeatSongs: [] });
    }
  },

  /**
   * 加载相似歌曲
   */
  loadSimilarSongs: function (songId) {
    if (!songId) {
      return;
    }

    // 直接获取相似歌曲，不再需要先获取风格标签
    this.getSimilarSongs();
  },

  /**
   * 获取相似歌曲
   */
  getSimilarSongs: function () {
    // 使用推荐新音乐接口替代相似音乐接口
    wx.request({
      url: "https://smartsound.top/personalized/newsong",
      method: "GET",
      data: {
        limit: 5, // 获取5首推荐新音乐
      },
      success: (res) => {
        if (res.data && res.data.result && res.data.result.length > 0) {
          // 处理返回的数据格式，提取所需信息
          const recommendSongs = res.data.result.map((item) => {
            // 确保歌曲信息的一致性
            return {
              id: item.id || (item.song && item.song.id),
              name: item.name || (item.song && item.song.name) || "未知歌曲",
              ar:
                item.song && item.song.artists
                  ? item.song.artists.map((artist) => ({
                      id: artist.id,
                      name: artist.name,
                    }))
                  : [{ id: 0, name: "未知歌手" }],
              al: {
                id: (item.song && item.song.album && item.song.album.id) || 0,
                name:
                  (item.song && item.song.album && item.song.album.name) ||
                  "未知专辑",
                picUrl:
                  item.picUrl ||
                  (item.song && item.song.album && item.song.album.picUrl) ||
                  "/assets/music-icon.png",
              },
              dt: (item.song && item.song.duration) || 0,
            };
          });

          // 保存推荐歌曲列表
          this.setData({ heartbeatSongs: recommendSongs });

          wx.showToast({
            title: "已获取推荐歌曲",
            icon: "none",
            duration: 1500,
          });
        } else {
          wx.showToast({
            title: "暂无推荐歌曲",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.error("获取推荐歌曲失败:", err);
        wx.showToast({
          title: "获取推荐歌曲失败",
          icon: "none",
        });
      },
    });
  },
});
